
package cn.jee.redis;

import cn.jee.redis.domain.Stu;
import redis.clients.jedis.Jedis;
import java.util.ArrayList;
import java.util.List;

public class StuMis {
  private Jedis jedis;

  public StuMis() {
    jedis = new Jedis();
  }

  // 清空数据库
  public void clear() {
    jedis.flushAll();

  }

  // 产生一个学生学号，自增
  public long newId() {
    return jedis.incr("stu:id:incr");
  }

  /**
   * 给Stu一个学号，存入Redis
   * 用hash表保存学生详细信息，sorted set存java、math成绩
   */
  public void add(Stu stu) {
    long id = newId();
    stu.setId(id);
    String key = "stu:" + id;
    jedis.hset(key, "id", String.valueOf(id));
    jedis.hset(key, "username", stu.getUsername());
    jedis.hset(key, "java", String.valueOf(stu.getJava()));
    jedis.hset(key, "math", String.valueOf(stu.getMath()));

    jedis.zadd("stu:java", stu.getJava(), String.valueOf(id));
    jedis.zadd("stu:math", stu.getMath(), String.valueOf(id));

  }
  /**
   * 数学成绩最高的5个人的姓名
   */
  public String[] top5ByMath() {
    List<String> idSet = jedis.zrevrange("stu:math", 0, 4);
    String[] names = new String[idSet.size()];
    int i = 0;
    for (String id : idSet) {
      names[i++] = jedis.hget("stu:" + id, "username");
    }
    return names;
  }
  /**
   * Java成绩在min和max之间的学生成绩数组
   */
  public double[] betweenJava(double min, double max) {
    List<String> idSet = jedis.zrangeByScore("stu:java", min, max);
    double[] scores = new double[idSet.size()];
    int i = 0;
    for (String id : idSet) {
      String javaScore = jedis.hget("stu:" + id, "java");
      scores[i++] = Double.parseDouble(javaScore);
    }
    return scores;
  }

  /**
   * 根据学号查找，没有找到返回null
   */
  public Stu findById(long id) {
    String key = "stu:" + id;
    if (!jedis.exists(key)) {
      return null;
    }
    Stu stu = new Stu();
    stu.setId(Long.parseLong(jedis.hget(key, "id")));
    stu.setUsername(jedis.hget(key, "username"));
    stu.setJava(Double.parseDouble(jedis.hget(key, "java")));
    stu.setMath(Double.parseDouble(jedis.hget(key, "math")));
    return stu;
  }

  /**
   * 按Java成绩从低到高分页查询
   */
  public List<Stu> pageByJava(int page, int size) {
    int start = (page - 1) * size;
    int end = start + size - 1;
    List<String> idSet = jedis.zrange("stu:java", start, end);
    List<Stu> list = new ArrayList<>();
    for (String id : idSet) {
      Stu stu = findById(Long.parseLong(id));
      if (stu != null) {
        list.add(stu);
      }
    }
    return list;
  }
}
